<template>
  <div>
    <el-date-picker
      v-model="searchValue"
      type="datetimerange"
      start-placeholder="起始时间"
      end-placeholder="最后时间"
      format="YYYY-MM-DD HH:mm:ss"
      date-format="YYYY/MM/DD ddd"
      time-format="A hh:mm:ss"
    />
    <el-button @click="searchButton">搜索</el-button>
    <el-button style="float: right; border: none; position: relative; top: 5px" @click="exportTable"
      >导出</el-button
    >
    <el-radio-group v-model="status" style="float: right; position: relative; right: 20px">
      <el-radio value="全部" size="large">全部</el-radio>
      <el-radio value="已通过" size="large">已通过</el-radio>
      <el-radio value="已拒绝" size="large">已拒绝</el-radio>
      <el-radio value="待审核" size="large">待审核</el-radio>
    </el-radio-group>
  </div>
  <el-table :data="currentPageData" style="width: 100%">
    <el-table-column fixed prop="id" label="订单编号" />
    <el-table-column prop="supplier" label="供应商" />
    <el-table-column prop="orderDate" label="订单日期" />
    <el-table-column prop="totalCost" label="总成本" />
    <el-table-column prop="status" label="状态" />
    <el-table-column prop="adminName" label="审核员" />
    <el-table-column fixed="right" label="操作">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
          审核
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :page-sizes="[5, 10, 20, 50, 100]"
    layout="total,sizes, prev, pager, next,"
    :total="total"
    style="float: right"
  >
  </el-pagination>
  <el-dialog v-model="dialogFormVisible" title="添加分类" width="500">
    <el-form :model="form">
      <el-form-item label="订单编号" :label-width="0">
        <el-input v-model="form.id" autocomplete="off" />
      </el-form-item>
      <el-form-item label="供应商" :label-width="0">
        <el-input v-model="form.supplier" autocomplete="off" />
      </el-form-item>
      <el-form-item label="订单日期" :label-width="0">
        <el-input v-model="form.orderDate" autocomplete="off" />
      </el-form-item>
      <el-form-item label="总成本" :label-width="0">
        <el-input v-model="form.totalCost" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态" :label-width="0">
        <el-select v-model="form.status" autocomplete="off">
          <el-option label="待审核" value="待审核" />
          <el-option label="已通过" value="已通过" />
          <el-option label="已拒绝" value="已拒绝" />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员编号" :label-width="0">
        <el-input v-model="form.adminId" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSure"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import myAxios from '../../axios/myAxios'
import { onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/userStore'
import moment from 'moment'
import ExcelJS from 'exceljs'
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
}
const form = reactive({
  id: '',
  supplier: '',
  orderDate: '',
  totalCost: '',
  status: '',
  adminId: '',
})
const isEdit = ref(false)
const idForEdit = ref(0)
const dialogFormVisible = ref(false)
const dialogSure = () => {
  if (isEdit.value) {
    myAxios
      .put('/purchase/update', {
        // id: idForEdit.value,
        id: form.id,
        supplier: form.supplier,
        orderDate: form.orderDate.replace(' ', 'T'),
        totalCost: form.totalCost,
        status: form.status,
        adminId: form.adminId,
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          init()
        } else {
          ElMessage({
            message: '修改失败',
            type: 'error',
          })
        }
      })
  } else {
    myAxios
      .post('/purchase/create', {
        supplier: form.supplier,
        totalCost: form.totalCost,
        status: form.status,
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          init()
        } else {
          ElMessage({
            message: '添加失败',
            type: 'error',
          })
        }
      })
  }
  form.adminId = ''
  form.id = ''
  form.supplier = ''
  form.orderDate = ''
  form.totalCost = ''
  form.status = ''
  dialogFormVisible.value = false
}
const userNow = useUserStore()
const userInfo = userNow.userInfo
const handleClick = (row) => {
  idForEdit.value = row.id
  form.adminId = row.adminId === userInfo.id ? row.adminId : userInfo.id
  form.id = row.id
  form.supplier = row.supplier
  form.orderDate = row.orderDate
  form.totalCost = row.totalCost
  form.status = row.status
  isEdit.value = true
  dialogFormVisible.value = true
}

const nameOfId = ref<{ [key: number]: string }>({})
const tableData = ref([])
const tableData2 = ref([])
const init = () => {
  myAxios.get('/purchase/list').then((res) => {
    if (res.data.code === 200) {
      tableData.value = res.data.data.records

      const names: { [key: number]: string } = {}
      myAxios.get('/user/list').then((res) => {
        res.data.data.records.map((item) => {
          names[item.id] = item.username
        })
        nameOfId.value = names
        tableData.value = tableData.value.map((item) => {
          return {
            ...item,
            orderDate: item.orderDate.replace('T', ' '),
            adminName: names[item.adminId],
          }
        })
        tableData2.value = tableData.value
        total.value = tableData.value.length
      })
    }
  })
}

const searchValue = ref('')
const searchButton = () => {
  if (!searchValue.value) {
    init()
  } else {
    tableData.value = tableData2.value.filter((item) => {
      if (
        moment(item.orderDate).isAfter(searchValue.value[0]) &&
        moment(item.orderDate).isBefore(searchValue.value[1])
      ) {
        return item
      } else if (
        moment(item.orderDate).isSame(searchValue.value[0]) ||
        moment(item.orderDate).isSame(searchValue.value[1])
      ) {
        return item
      }
    })
    total.value = tableData.value.length
  }
}
const status = ref('全部')
watch(status, (newVal) => {
  if (newVal !== '全部') {
    tableData.value = tableData2.value.filter((item) => item.status === newVal)
    total.value = tableData.value.length
  } else {
    init()
  }
})

const exportTable = () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  worksheet.columns = [
    { header: '订单编号', key: 'id', width: 10 },
    { header: '供应商', key: 'supplier', width: 10 },
    { header: '订单日期', key: 'orderDate', width: 20 },
    { header: '总成本', key: 'totalCost', width: 20 },
    { header: '状态', key: 'status', width: 20 },
    { header: '审核员', key: 'adminId', width: 20 },
  ]
  const datas = tableData.value.map((item) => {
    return {
      id: item.id,
      supplier: item.supplier,
      orderDate: item.orderDate,
      totalCost: item.totalCost,
      status: item.status,
      adminId: nameOfId.value[item.adminId],
    }
  })
  datas.forEach((rowData) => {
    worksheet.addRow(rowData)
  })
  workbook.xlsx.writeBuffer().then((buffer) => {
    const blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '订单审核详情.xlsx'
    a.click()
  })
}

onMounted(() => {
  init()
})
</script>
